package com.wangye.http.util;

import com.alibaba.fastjson.JSONObject;
import com.wangye.mp.constant.MPConstantUtil;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by 王叶 on 2018/3/14.
 */
public class HttpClientUtil {

    /**
     * 执行  GET 请求
     * @param url    接口
     * @param map    请求参数键值对  key = value
     * @return
     */
    public static JSONObject executeGet(String url,Map<String,Object> map){
        List<NameValuePair> requestParams = HttpClientUtil.setRequestParams(map);//设置  请求参数
        return executeGet(url,requestParams);
    }

    /**
     * 执行  GET 请求
     * @param url    接口
     * @param data    请求参数键值对  key = value
     * @return
     */
    public static JSONObject executeGet(String url,JSONObject data){
        List<NameValuePair> requestParams = HttpClientUtil.setRequestParams(data);//设置  请求参数
        return executeGet(url, requestParams);
    }

    /**
     * 执行 GET  请求
     * @param url    接口URL
     * @param requestParams     请求参数键值对  key = value
     * @return
     */
    public static JSONObject executeGet(String url,List<NameValuePair> requestParams) {
        JSONObject jsonObject = null;
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            String param = EntityUtils.toString(new UrlEncodedFormEntity(requestParams, MPConstantUtil.DEFAULT_CHARSET));
            System.out.println("param:"+param);
            HttpGet httpGet = new HttpGet(url+"?"+param);
            //执行 get请求
            response = httpClient.execute(httpGet);
            jsonObject = HttpClientUtil.getJsonObject(response);
            HttpEntity resEntity = response.getEntity();
            EntityUtils.consume(resEntity);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if ( httpClient != null)
                    httpClient.close();
                if (response != null )
                    response.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return jsonObject;
    }

    /**
     *  组装 请求参数
     * @param map 请求参数键值对  key = value
     * @return
     */
    public static List<NameValuePair> setRequestParams(Map<String,Object> map){
        List<NameValuePair> RequestParams = null;
        if (map == null || map.size() == 0) {
            return  new ArrayList<NameValuePair>();
        }
         RequestParams = new ArrayList<NameValuePair>(map.size()); //设置 请求参数
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            RequestParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));//把参数放入请求中
        }
        return RequestParams;
    }

    /**
     *  组装 请求参数
     * @param data 请求参数键值对  key = value
     * @return
     */
    public static List<NameValuePair> setRequestParams(JSONObject data){
        List<NameValuePair> RequestParams = null;
        if (data == null || data.size() == 0) {
            return  new ArrayList<NameValuePair>();
        }
        RequestParams = new ArrayList<NameValuePair>(data.size()); //设置 请求参数
        for (Map.Entry<String, Object> entry : data.entrySet()) {
            RequestParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));//把参数放入请求中
        }
        return RequestParams;
    }
    /**
     *  获取 response中的 jsonObject
     * @param response
     * @return
     */
    public static JSONObject getJsonObject(CloseableHttpResponse response){
        HttpEntity entity = response.getEntity();
        try {
            return JSONObject.parseObject(EntityUtils.toString(entity, MPConstantUtil.DEFAULT_CHARSET));
        }catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }



    /**
     * 执行POST请求  请求数据通过JSON格式传输
     * @param url
     * @param param     JSON数据
     * @return
     */
    public static JSONObject executePostByJson(String url,JSONObject param){
        JSONObject jsonObject = null;
        CloseableHttpResponse response = null;

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);

        try {
            StringEntity entity = new StringEntity(param.toString(),"utf-8");//解决中文乱码问题
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);

            //执行 post请求
            response = httpClient.execute(httpPost);
            jsonObject = HttpClientUtil.getJsonObject(response);
            HttpEntity resEntity = response.getEntity();
            EntityUtils.consume(resEntity);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if ( httpClient != null)
                    httpClient.close();
                if (response != null )
                    response.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return jsonObject;
    }

    /**
     * 执行 POST请求
     * @param url           接口
     * @param map           请求参数键值对  key = value
     * @return
     */
    public static JSONObject executePost(String url,Map<String,Object> map) {
        JSONObject jsonObject = null;
        CloseableHttpResponse response = null;

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);

        try {
            List<NameValuePair> requestParams = HttpClientUtil.setRequestParams(map);//设置  请求参数
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(requestParams, MPConstantUtil.DEFAULT_CHARSET);    //设置 请求的编码格式
            httpPost.setEntity(urlEncodedFormEntity);

            //执行 post请求
            response = httpClient.execute(httpPost);
            jsonObject = HttpClientUtil.getJsonObject(response);
            HttpEntity resEntity = response.getEntity();
            EntityUtils.consume(resEntity);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if ( httpClient != null)
                    httpClient.close();
                if (response != null )
                    response.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return jsonObject;
    }

}
